﻿using System;
using System.Collections.Generic;

namespace SocialFilter.model
{
	class Filter
	{
		private List<string> includeFilters = new List<string>();
		private List<string> excludeFilters = new List<string>();
		
		public Filter( string _filterString )
		{		
			//TODO: escape characters \+ \- \\
			
			// parse filter from string
			string filterString = _filterString.Trim();
			if ( filterString == "" )
			{
				return;
			}
			//search for "+" or "-"
			char prevSign = '+';
			int prevPosition = 0;
			int nextPlus = filterString.IndexOf('+', 0);
			int nextMinus = filterString.IndexOf('-', 0);
			int nextPosition = 0;
			string keyPhrase = "";
			do
			{
				nextPosition = nextPlus;
				if ( nextMinus < nextPlus && nextMinus > -1 || nextPlus < 0 )
				{
					nextPosition = nextMinus;
				}
				
				if ( nextPosition < 0 ) // No + or - found
				{
					nextPosition = filterString.Length;
				}

				//add string to proper filter
				keyPhrase = filterString.Substring(prevPosition, nextPosition - prevPosition).Trim();

				//find next filter string
				if (keyPhrase != "")
				{
					if (prevSign == '+')
					{
						includeFilters.Add(keyPhrase.ToLower());
					}
					else if (prevSign == '-')
					{
						excludeFilters.Add(keyPhrase.ToLower());
					}
				}
				
				//update nextPlus or nextMinus
				if ( (nextPlus < nextMinus || nextMinus < 0) && nextPlus > -1 ) //plus
				{
					prevSign = '+';
					prevPosition = nextPlus + 1;
					nextPlus = filterString.IndexOf('+', nextPlus + 1);
				}
				else if ( nextMinus > -1 )//minus
				{
					prevSign = '-';
					prevPosition = nextMinus + 1;
					nextMinus = filterString.IndexOf('-', nextMinus + 1);
				}
			} while ( nextPosition < filterString.Length );
		}

		public bool FilterItem(FeedItem _item)
		{
			//apply include filters
			string lowerCaseContent = _item.Content.ToLower();
			string lowerCaseAuthor = _item.Author.ToLower();
			
			for ( int i = 0; i < includeFilters.Count; ++i )
			{
				if (  lowerCaseContent.Contains(includeFilters[i]) == false && 
					lowerCaseAuthor.Contains(includeFilters[i]) == false )
				{
					return false;
				}
			}
			//apply exclude filters
			for ( int i = 0; i < excludeFilters.Count; ++i )
			{
				if (lowerCaseContent.Contains(excludeFilters[i]) == true ||
					lowerCaseAuthor.Contains(excludeFilters[i]) == true)
				{
					return false;
				}
			}
			return true;
		}
	}
}